import { message } from "antd";
import { BASE_URL } from "./config";
import qs from "qs";
export declare interface ReturnType {
  data: any;
  msg: string;
  message?:string
  status: string;
}
type paramsType = {
  body: string | FormData;
  method: "post";
};
const statusMsg = {
  500:'服务器错误❎',
  404:'接口错误❎',
  400:'客户端错误❎'
}

const LoginInfo = sessionStorage.userInfo?JSON.parse(sessionStorage.userInfo):''
const Request = <T extends ReturnType>(
  url: string,
  obj?: object
): Promise<T> => {
  return new Promise((resolve, reject) => {
    fetch(BASE_URL + url, obj)
      .then((s: Response) => s.json())
      .then((result: T) => {
        if (result.status !== "0") {
          // const msg = statusMsg[result.status]? statusMsg[result.status]:`${result.status}~~❎${result?.msg||result?.message}`
          message.error(result.msg);
        }
        resolve(result);
      })
      .catch((err: any) => {
        message.error("接口异常 😈");
        reject(err);
      });
  });
};

const headersConfig = {
  headers: LoginInfo.userToken?{
    Accept: "application/json",
    "content-type": "application/x-www-form-urlencoded",
    "token": LoginInfo.userToken
  }:{
    Accept: "application/json",
    "content-type": "application/x-www-form-urlencoded",
  },
};

export class FetchRequest<T extends ReturnType> {
  post(url: string, param?: object | undefined): Promise<T> {
    const body = qs.stringify(param);
    const params: paramsType = {
      body,
      method: "post",
      ...headersConfig,
    };
    return Request(url, params);
  }
  put(url: string, body: FormData): Promise<T> {
    const params: paramsType = {
      body,
      method: "post",
    };
    return Request(url, params);
  }
}
export default FetchRequest;
